﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace IOP.OpenType.Rasterizer
{
    /// <summary>
    /// SDF算法用网格
    /// </summary>
    public struct SDFGrid
    {
        /// <summary>
        /// 
        /// </summary>
        public static readonly Point Inside = Point.Empty;
        /// <summary>
        /// 
        /// </summary>
        public static readonly Point Empty = new Point(9999, 9999);
        /// <summary>
        /// 距离矩阵
        /// </summary>
        public Point[,] Distance;
        /// <summary>
        /// 获取某个点的距离
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public Point GetDistance(int x, int y)
        {
            if (Distance == null) return Empty;
            int height = Distance.GetLength(0);
            int width = Distance.GetLength(1);
            if (x >= 0 && y >= 0 && x < width && y < height) return Distance[y, x];
            else return Empty;
        }
        /// <summary>
        /// 设置某个点的距离
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="point"></param>
        public void SetDistance(int x, int y, Point point)
        {
            if (Distance == null) return;
            int height = Distance.GetLength(0);
            int width = Distance.GetLength(1);
            if (x >= 0 && y >= 0 && x < width && y < height) Distance[y, x] = point;
            else return;
        }
        /// <summary>
        /// 清理所有数据
        /// </summary>
        public void Clear()
        {
            if (Distance == null) return;
            Array.Clear(Distance, 0, Distance.Length);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="distance"></param>
        /// <returns></returns>
        public static double DistSq(Point distance) => distance.X * distance.X + distance.Y * distance.Y;
        /// <summary>
        /// 比较
        /// </summary>
        /// <param name="distance"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="offsetX"></param>
        /// <param name="offsetY"></param>
        /// <returns></returns>
        public void Compare(ref Point distance, int x, int y, int offsetX, int offsetY)
        {
            Point other = GetDistance(x + offsetX, y + offsetY);
            other.X += offsetX;
            other.Y += offsetY;
            if (DistSq(other) < DistSq(distance))
                distance = other;
        }
    }
}
